package com.example.computer_exam_training_sys.service.impl;

import com.example.computer_exam_training_sys.dto.LearningGoalDTO;
import com.example.computer_exam_training_sys.entity.UserLearningGoal;
import com.example.computer_exam_training_sys.mapper.UserLearningGoalMapper;
import com.example.computer_exam_training_sys.service.UserLearningGoalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserLearningGoalServiceImpl implements UserLearningGoalService {

    @Autowired
    private UserLearningGoalMapper goalMapper;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public List<LearningGoalDTO> getUserGoals(Long userId) {
        List<UserLearningGoal> goals = goalMapper.findByUserId(userId);
        return goals.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public LearningGoalDTO createGoal(Long userId, String goalType, Integer targetValue,
                                    String startDate, String endDate) {
        UserLearningGoal goal = new UserLearningGoal();
        goal.setUserId(userId);
        goal.setGoalType(goalType);
        goal.setTargetValue(targetValue);
        goal.setCurrentValue(0);
        goal.setStartDate(LocalDate.parse(startDate, DATE_FORMATTER));
        goal.setEndDate(LocalDate.parse(endDate, DATE_FORMATTER));
        goal.setStatus("active");
        
        goalMapper.insert(goal);
        return convertToDTO(goal);
    }

    @Override
    public LearningGoalDTO updateGoalProgress(Long goalId, Integer currentValue) {
        UserLearningGoal goal = goalMapper.findById(goalId);
        if (goal == null) {
            throw new RuntimeException("目标不存在");
        }
        
        String status = currentValue >= goal.getTargetValue() ? "completed" : "active";
        goalMapper.updateProgress(goalId, currentValue, status);
        
        goal = goalMapper.findById(goalId);
        return convertToDTO(goal);
    }

    @Override
    public List<LearningGoalDTO> getGoalCompletionStatus(Long userId) {
        List<UserLearningGoal> activeGoals = goalMapper.findActiveGoals(userId);
        List<UserLearningGoal> completedGoals = goalMapper.findCompletedGoals(userId);
        
        List<LearningGoalDTO> allGoals = activeGoals.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        allGoals.addAll(completedGoals.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList()));
        
        return allGoals;
    }

    @Override
    public List<LearningGoalDTO> getGoalSuggestions(Long userId) {
        // 这里可以实现基于用户历史数据的智能建议逻辑
        // 示例：根据用户当前进度和目标完成情况生成建议
        List<UserLearningGoal> activeGoals = goalMapper.findActiveGoals(userId);
        return activeGoals.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private LearningGoalDTO convertToDTO(UserLearningGoal goal) {
        LearningGoalDTO dto = new LearningGoalDTO();
        dto.setGoalId(goal.getGoalId());
        dto.setUserId(goal.getUserId());
        dto.setGoalType(goal.getGoalType());
        dto.setTargetValue(goal.getTargetValue());
        dto.setCurrentValue(goal.getCurrentValue());
        dto.setStartDate(goal.getStartDate());
        dto.setEndDate(goal.getEndDate());
        dto.setStatus(goal.getStatus());
        dto.setCreateTime(goal.getCreateTime());
        dto.setUpdateTime(goal.getUpdateTime());
        dto.setUserName(goal.getUserName());
        
        // 计算完成率
        if (goal.getTargetValue() > 0) {
            double completionRate = (double) goal.getCurrentValue() / goal.getTargetValue() * 100;
            dto.setCompletionRate(Math.min(completionRate, 100));
        }
        
        // 计算剩余天数
        if (goal.getEndDate() != null) {
            LocalDate today = LocalDate.now();
            long remainingDays = ChronoUnit.DAYS.between(today, goal.getEndDate());
            dto.setRemainingDays((int) Math.max(remainingDays, 0));
        }
        
        return dto;
    }
} 